<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="100px">
      <el-form-item label="外部设备编号" prop="outeqCode">
        <el-input style="width: 230px" v-model="queryParams.outeqCode" clearable placeholder="请输入外部设备编号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备状态" prop="eqState">
        <el-input style="width: 230px" v-model="queryParams.eqState" clearable placeholder="请输入设备状态" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备类型" prop="eqType">
        <el-select style="width: 230px" v-model="queryParams.eqType" clearable="true" placeholder="请选择设备类型">
          <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['device:device:add']" icon="Edit" plain type="primary" @click="ocated">下拨 </el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="外部设备编号" prop="outeqCode" />
      <el-table-column align="center" label="终端绑定设备号" prop="eqCode" width="200" />
      <el-table-column align="center" label="设备状态" prop="eqState">
        <template #default="scope">
          <dict-tag :options="eq_state" :value="scope.row.eqState" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="下拨状态" prop="agentAllocatedStatus">
        <template #default="scope">
          <dict-tag :options="allocated_status" :value="scope.row.agentAllocatedStatus" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="商户绑定状态" prop="tenantBuild">
        <template #default="scope">
          <dict-tag :options="tenant_build" :value="scope.row.tenantBuild" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="设备类型" prop="eqType">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.eqType" />
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="400">
        <template #default="scope">
          <el-button v-hasPermi="['device:device:edit']" icon="Edit" type="text" @click="handleUpdate(scope.row, 2)"> 下拨 </el-button>

          <el-button v-if="scope.row.tenantBuild == 0" v-hasPermi="['device:device:edit']" icon="Edit" type="text" @click="handleUpdate(scope.row, 1)"> 绑定 </el-button>

          <el-button
            v-if="scope.row.tenantBuild == 1"
            v-hasPermi="['device:device:edit']"
            icon="Edit"
            style="color: #f56c6c"
            type="text"
            @click="handleUpdate(scope.row, 1)"
          >
            解绑
          </el-button>

          <el-button v-hasPermi="['device:device:edit']" icon="View" type="text" @click="handQuery(scope.row)"> 商户 </el-button>

          <el-button v-hasPermi="['device:device:edit']" icon="View" type="text" @click="handleCheck(scope.row)"> 交易 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    <!-- 绑定代理商 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合伙人" prop="eqType">
          <el-select v-model="buildId" :clearable="true" :filterable="true" placeholder="请选择合伙人">
            <el-option v-for="item in userlist" :key="item.id" :label="item.agentName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="ocatedSubmit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看商户详情 -->
    <el-dialog v-if="fromData" v-model="openQuery" :title="titles" append-to-body width="1000px">
      <el-descriptions :column="3" border class="margin-top" title="商户详情">
        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 商户名称</div>
          </template>
          {{ fromData.commercialTenantName }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 商户编号</div>
          </template>
          {{ fromData.commercialTenantNo }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 商户手机号</div>
          </template>
          {{ fromData.commercialTenantPhone }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 商户类型</div>
          </template>
          <dict-tag :options="commercial_tenant_state" :value="fromData.commercialTenantState" />
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 邮件</div>
          </template>
          {{ fromData.commercialTenantEmil }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 贷记卡费率</div>
          </template>
          {{ fromData.commercialCardpayFeeRate }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 借记卡费率</div>
          </template>
          {{ fromData.commercialCardpayDebitRate }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 封顶值</div>
          </template>
          {{ fromData.commercialCardpayDebitCap }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 扫码优惠费率</div>
          </template>
          {{ fromData.commercialPreferstageFeerate }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 微信费率</div>
          </template>
          {{ fromData.commercialWxpayFeerate }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 支付宝费率</div>
          </template>
          {{ fromData.commercialAlipayFeerate }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 外部商户号</div>
          </template>
          {{ fromData.outmerchantno }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 商户状态</div>
          </template>
          {{ fromData.status }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 登录名称</div>
          </template>
          {{ fromData.nickName }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 最后登录IP</div>
          </template>
          {{ fromData.loginIp }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item"> 最后登录时间</div>
          </template>
          {{ fromData.loginDate }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 添加或修改来钱乐终端对话框 -->
    <el-drawer v-model="buildTenant" :title="title" append-to-body size="45%">
      <el-form ref="terminalRef" :model="formDevice" :rules="terRules" label-width="100px">
        <el-form-item :label="title" prop="eqType">
          <el-select v-model="buildId" :clearable="true" :filterable="true" placeholder="请选择">
            <el-option v-for="item in userlist" :key="item.id" :label="item.commercialTenantName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="签购单名称" prop="terminalName">
          <el-input v-model="formDevice.terminalName" placeholder="请输入签购单名称" />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactTel">
          <el-input v-model="formDevice.contactTel" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="安装地址" prop="installAddress">
          <el-input v-model="formDevice.installAddress" placeholder="请输入安装地址" />
        </el-form-item>

        <el-form-item label="省市区" required>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="installProvince">
                <el-select v-model="formDevice.installProvince" :clearable="true" placeholder="请选择省" @change="handleProvinceChange">
                  <el-option v-for="item1 in provinceOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="installCity">
                <el-select v-model="formDevice.installCity" :clearable="true" placeholder="请选择市" @change="handleCityChange">
                  <el-option v-for="item1 in cityOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="installDistrict">
                <el-select v-model="formDevice.installDistrict" :clearable="true" placeholder="请选择区">
                  <el-option v-for="item1 in districtOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row>
          <el-form-item label="交易权限-查询" label-width="150px" prop="isOpenConsume">
            <el-switch v-model="formDevice.isOpenConsume" />
          </el-form-item>
          <el-form-item label="交易权限-退货" label-width="150px" prop="isOpenRefund">
            <el-switch v-model="formDevice.isOpenRefund" />
          </el-form-item>
          <el-form-item label="交易权限-消费类" label-width="150px" prop="isOpenQueryTrade">
            <el-switch v-model="formDevice.isOpenQueryTrade" />
          </el-form-item>
          <el-form-item label="交易权限-预授权类" label-width="150px" prop="isOpenPreauthorize">
            <el-switch v-model="formDevice.isOpenPreauthorize" />
          </el-form-item>
          <el-form-item label="卡类型权限-借记卡" label-width="150px" prop="isOpenDebitCard">
            <el-switch v-model="formDevice.isOpenDebitCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-贷记卡" label-width="150px" prop="isOpenCreditCard">
            <el-switch v-model="formDevice.isOpenCreditCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-准贷记卡" label-width="150px" prop="isOpenSemiCreditCard">
            <el-switch v-model="formDevice.isOpenSemiCreditCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-预付费卡" label-width="150px" prop="isOpenPrepaidCard">
            <el-switch v-model="formDevice.isOpenPrepaidCard" />
          </el-form-item>
          <el-form-item label="交易权限-二维码预授权类" label-width="190px" prop="isOpenPreauthorizeQr">
            <el-switch v-model="formDevice.isOpenPreauthorizeQr" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-alert :closable="false" class="mb20" show-icon title="温馨提示：同地址请上传增机单,否则请上传门店照片(最多支持5张)" type="info" />
          <el-col v-for="(item1, index1) in formDevice.fileList" :key="item1" :span="8">
            <el-form-item :label="`上传图片`" :prop="`imgList[${index1}].path`" label-width="80px">
              <ImageUpload1 v-model="item1.path" />
              <div class="img-wrap">
                <el-button
                  v-if="index1 + 1 === formDevice.fileList.length && formDevice.fileList.length < 5"
                  type="primary"
                  @click="formDevice.fileList.push({ path: null })"
                >
                  添加
                </el-button>
                <el-button v-if="formDevice.fileList.length > 1" type="danger" @click="formDevice.fileList.splice(index1, 1)">删除 </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="TerSubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" name="Device" setup>
  import { addDevice, getDevice, listDevice, ocatedApi, updateDevice } from '@/api/device/device';
  import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
  import { getUser, listUser, listUsers } from '@/api/tenant/user';
  import { areaListByParentId } from '@/api/laiqianle/register';
  import ImageUpload1 from '@/components/ImageUploadThis';
  import router from '@/router';

  import { listAgent, listAgents } from '@/api/agent/agent';
  const { proxy } = getCurrentInstance();
  const { device_type, allocated_status, sys_my_yes_no_number, tenant_build, eq_state } = proxy.useDict(
    'sys_my_yes_no_number',
    'device_type',
    'allocated_status',
    'tenant_build',
    'eq_state',
  );

  const { commercial_tenant_state } = proxy.useDict('commercial_tenant_state');
  const buildId = ref(null);
  let states = ref(null);
  const deviceList = ref([]);
  const userlist = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('下拨机具');
  const openQuery = ref(false);
  const titles = ref('');
  const fromData = ref({});
  const buildTenant = ref(false);
  const data = reactive({
    form: {},
    formDevice: {
      id: null,
      outMerchantNo: null,
      outTerminalNo: null,
      terminalName: null,
      deviceSn: null,
      contactTel: null,
      installAddress: null,
      installProvince: null,
      installCity: null,
      installDistrict: null,
      isOpenConsume: true,
      isOpenRefund: true,
      isOpenQueryTrade: true,
      isOpenPreauthorize: true,
      isOpenDebitCard: true,
      isOpenCreditCard: true,
      isOpenSemiCreditCard: true,
      isOpenPrepaidCard: true,
      isOpenPreauthorizeQr: true,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      delFlag: null,
      fileList: [{ path: null }],
    },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      agentId: null,
      eqCode: null,
      outeqCode: null,
      eqState: null,
      agentAllocatedStatus: 0,
      eqType: null,
      equipmentId: null,
    },
    rules: {},
    queryUserParams: {
      commercialTenantState: null,
    },

    terRules: {
      outMerchantNo: [{ required: true, message: '外部商户号不能为空', trigger: 'blur' }],
      outTerminalNo: [{ required: true, message: '外部终端号不能为空', trigger: 'blur' }],
      terminalName: [{ required: true, message: '签购单名称不能为空', trigger: 'blur' }],
      contactTel: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
      installAddress: [{ required: true, message: '安装地址不能为空', trigger: 'blur' }],
      installProvince: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
      installCity: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
      installDistrict: [{ required: true, message: '区县不能为空', trigger: 'blur' }],
    },
  });

  const { queryParams, form, rules, queryUserParams, formDevice, terRules } = toRefs(data);

  /** 查询机具管理列表 */
  function getList() {
    loading.value = true;
    listDevice(queryParams.value).then((response) => {
      deviceList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      agentId: null,
      tenant_build: null,
      tenantId: null,
      eqCode: null,
      outeqCode: null,
      eqState: null,
      agentAllocatedStatus: 0,
      eqType: null,
      equipmentId: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      delFlag: null,
    };
    // userList.value = null;
    proxy.resetForm('deviceRef');
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm('queryRef');
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = '添加机具管理';
  }

  // 省市区
  interface provinces {
    id: number;
    name: string;
    code: string;
    pcode: string;

    [key: string]: any;
  }

  let provinceOptions = ref<provinces[]>([]);
  let cityOptions = ref<provinces[]>([]);
  let districtOptions = ref<provinces[]>([]);
  const getProvinceList = async (parentId) => {
    if (parentId === '') return [];
    const { data } = await areaListByParentId(parentId);
    return data;
  };
  provinceOptions.value = await getProvinceList(0);

  const handleProvinceChange = async (value) => {
    cityOptions.value = await getProvinceList(value);
    form.value['installCity'] = null;
    form.value['installDistrict'] = null;
  };

  const handleCityChange = async (value) => {
    districtOptions.value = await getProvinceList(value);
    form.value['installDistrict'] = null;
  };

  /** 修改按钮操作 */
  function handleUpdate(row, state) {
    reset();
    const _id = row.id || ids.value;
    states = state;
    getDevice(_id).then(async (response) => {
      form.value = response.data;
      if (state === 1) {
        buildTenant.value = true;
        buildId.value = form.value.tenantId;
        title.value = '绑定商户';
        cityOptions.value = await getProvinceList(response.data.installProvince);
        districtOptions.value = await getProvinceList(response.data.installCity);
      } else {
        open.value = true;
        // buildId.value = form.value.agentId;
        form.value.allocatedStatus = 1;
        title.value = '下拨机具';
      }
    });
    queryUserParams.value.commercialTenantState = state;
    getTenantList();
  }

  /**查看商户信息 */
  function handQuery(row) {
    reset();
    const id = row.tenantId;
    getUser(id).then((response) => {
      console.log(response);
      openQuery.value = true;
      fromData.value = response.data;
      titles.value = '查看商户详情';
    });
  }

  function handleCheck(row) {
    reset();
    console.log(row);
    router.push({
      path: '/pay/deal',
      query: {
        eqCode: row.eqCode,
      },
    });
  }

  /**
   * 终端提交
   * @constructor
   */
  function TerSubmitForm() {
    proxy.$refs['terminalRef'].validate((valid) => {
      if (valid) {
        if (form.value.id != null) {
          if (states.value === 1) {
            // 设置商户
            form.value.tenantId = buildId;
            // 设置绑定值
            form.value.tenantBuild = 1;
            // 设置终端信息
            form.value.tenantDevice = formDevice.value;
            form.value.buildState = 1;
          } else {
            form.value.buildState = 0;
            form.value.agentId = buildId;
          }
          updateDevice(form.value).then((response) => {
            proxy.$modal.msgSuccess('修改成功');
            buildTenant.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs['deviceRef'].validate((valid) => {
      if (valid) {
        if (form.value.id != null) {
          if (states.value === 1) {
            // 设置商户
            form.value.tenantId = buildId;
            // 设置绑定值
            form.value.tenantBuild = 1;
            // 设置终端信息
            form.value.tenantDevice = formDevice.value;
          } else {
            form.value.buildState = 0;
            form.value.agentId = buildId;
          }
          updateDevice(form.value).then((response) => {
            proxy.$modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addDevice(form.value).then((response) => {
            proxy.$modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  // function handleDelete(row) {
  //   const _ids = row.id || ids.value;
  //   proxy.$modal
  //     .confirm('是否确认删除机具管理编号为"' + _ids + '"的数据项？')
  //     .then(function () {
  //       return delDevice(_ids);
  //     })
  //     .then(() => {
  //       getList();
  //       proxy.$modal.msgSuccess('删除成功');
  //     })
  //     .catch(() => {
  //     });
  // }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download(
      'device/device/export',
      {
        ...queryParams.value,
      },
      `device_${new Date().getTime()}.xlsx`,
    );
  }

  /** 查询商户列表 */
  const getTenantList = async () => {
    const { data } = await listAgents(queryUserParams.value);
    userlist.value = data;
  };

  function ocated() {
    // queryUserParams.value.commercialTenantState = 2;
    getTenantList();
    open.value = true;
  }

  /**
   * 机具拨动
   */
  function ocatedSubmit() {
    const _ids = form.value.id || ids.value;
    form.value.agentAllocatedStatus = 1;
    form.value.buildState = 0;
    form.value.agentId = buildId;
    title.value = '机具下拨';
    proxy.$refs['deviceRef'].validate((valid) => {
      if (valid) {
        ocatedApi(_ids, form.value).then((res) => {
          proxy.$modal.msgSuccess('机具下拨成功');
          open.value = false;
          buildId.value = null;
          getList();
        });
      }
    });
  }

  getList();
</script>
